
package article

import (
	"strconv"
	"git.oschina.net/fuxiaohei/fuxiaohei-go.git/Core"
	"git.oschina.net/fuxiaohei/fuxiaohei-go.git/Rt"
)

// get list of article
func GetList(page int, size int, condition map[string]string, pageUrl string) ([]map[string]string, string) {
	// two sql for get data and count data
	sql := Core.Sql("fuxiaohei_articles", "id,title,slug,desc,add_time,comments,views,status,category,author").Paged(page, size).Order("id DESC").Where("status != ?")
	sql2 := Core.Sql("fuxiaohei_articles").Where("status != ?")
	args := []interface {}{"draft"}
	if len(condition) > 0 {
		for k, v := range condition {
			sql.Where(k + " = ?")
			sql2.Where(k + " = ?")
			args = append(args, v)
		}
	}
	articles := Core.Db.All(sql.Select(), args...)
	counts := Core.Db.One(sql2.Count(), args...)
	if len(counts) < 1 {
		return articles, ""
	}
	tmpCategories := make(map[string]map[string]string)
	tmpUsers := make(map[string]map[string]string)
	// fill category and user info in article map
	for k, v := range articles {
		if tmpCategories[v["category"]] == nil {
			tmpCategories[v["category"]] = categoryGetById(v["category"])
		}
		articles[k]["category_title"] = tmpCategories[v["category"]]["title"]
		articles[k]["category_slug"] = tmpCategories[v["category"]]["slug"]
		if tmpUsers[v["author"]] == nil {
			tmpUsers[v["author"]] = userGetOne(v["author"])
		}
		articles[k]["author_name"] = tmpUsers[v["author"]]["real_name"]
		articles[k]["author_user"] = tmpUsers[v["author"]]["user"]
		articles[k]["author_role"] = tmpUsers[v["author"]]["role_name"]
	}
	count, _ := strconv.Atoi(counts["countNum"])
	// create pager rendered html
	return articles, Rt.Pager.Html(Rt.Pager.Calculate(page, size, count), pageUrl, 1)
}

// get one article by condition
func GetByCondition(condition map[string]string) map[string]string {
	if len(condition) < 1 {
		return nil
	}
	sql := Core.Sql("fuxiaohei_articles", "id,title,slug,content,add_time,comments,views,status,category,author").Where("status != ?")
	args := []interface {}{"draft"}
	for k, v := range condition {
		sql.Where(k + " = ?")
		args = append(args, v)
	}
	article := Core.Db.One(sql.Select(), args...)
	if len(article) < 1 {
		return nil
	}
	category := categoryGetById(article["category"])
	article["category_title"] = category["title"]
	article["category_slug"] = category["slug"]
	user := userGetOne(article["author"])
	article["author_name"] = user["real_name"]
	article["author_user"] = user["user"]
	article["author_role"] = user["role_name"]
	return article
}

func PopList(size int) []map[string]string {
	sql := Core.Sql("fuxiaohei_articles", "id,title,slug,comments").Order("comments DESC").Where("status != ?").Limit(size)
	return Core.Db.All(sql.Select(), "draft")
}

// increase view count
func IncreaseView(id string) {
	sql := "UPDATE fuxiaohei_articles SET views = views + 1 WHERE id = ?"
	Core.Db.Exec(sql, id)
}


